package com.csdj.game.service;

import com.csdj.game.constant.CommonConstant;
import com.csdj.game.constant.ResultCodeContant;
import com.csdj.game.entity.LoginHis;
import com.csdj.game.entity.User;
import com.csdj.game.mapper.LoginHisMapper;
import com.csdj.game.mapper.UserMapper;
import com.csdj.game.util.EncryptUtil;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * author:cloud
 * date:2021/3/30 0030
 **/

@Service
public class UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private LoginHisMapper loginHisMapper;

    private Logger log = Logger.getLogger(UserService.class);

    /**
     * 登录
     * 对密码进行md5转换，登录成功后添加username,role到session
     * 添加登录记录
     * @param request
     * @param username
     * @param password
     * @return
     */
    public boolean login(HttpServletRequest request,String username, String password){
        //对密码进行md5计算
        String dePass = EncryptUtil.getMd5(password);
        User user = userMapper.login(username,dePass);
        if(user == null){
            //用户不存在， 登录失败 用户名或是密码错误
            return false;
        }
        //登录成功,将用户名保存到session 以便登录拦截器核验
        HttpSession session = request.getSession();
        session.setAttribute("username",username);
        session.setAttribute("role",user.getRole());
        //添加登录记录
        LoginHis his = new LoginHis();
        his.setUserId(user.getId());
        his.setLoginTm(new Date());
        his.setLoginIp(request.getRemoteHost());
        int insert = loginHisMapper.insert(his);
        if(insert == 0){
            //添加失败
            log.error("添加用户登录记录失败");
        }
        return true;
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    public int regist(User user){
        //判断用户名是否存在
        int res = userMapper.findCountByUsername(user.getUsername());
        if(res>0){
            //用户已经存在
            return ResultCodeContant.USER_EXISTS;
        }
        //对密码进行hash加密
        String depass = EncryptUtil.getMd5(user.getPassword());
        user.setPassword(depass);
        user.setRegTm(new Date());
        user.setUpdateTm(new Date());
        user.setRole(CommonConstant.ROLE_DEV);
        //保存数据 注册成功
        res = userMapper.insert(user);
        if(res > 0){
            return ResultCodeContant.SUCCESS;
        }
        return ResultCodeContant.FAIL;
    }
}
